<template>
    <div class="score-summary-container">
        <global-search @submitSearch="submitSearch" class="global-tool-search" :showDoctor="true"/>
        <div class="page-content">
            <div class="head">
                <h3>医师缺陷类型分析</h3>
                <btn-group :showBtn="showBtn" :code="{exportCode: 100003000004}" @toExport="toExport"/>
            </div>
            <el-table
                ref="tableData"
                :data="tableData"
                tooltip-effect="light"
                border
                :max-height="tableHeight"
                :cell-class-name="colClass"
                class="data-table">
                <el-table-column
                    prop="resident"
                    label="住院医师"
                    width="120"
                    align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    label="总病案例数"
                    prop="total"
                    align="center"
                    width="120">
                    <template slot-scope="scope">
                        <span v-if="scope.row.total > 0" class="to-child-page" @click="toMRList(scope.row, 0)">{{scope.row.total}}</span>
                        <span v-else>{{scope.row.total}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="非编码缺陷病案例数"
                    width="160"
                    align="center"
                    prop="noneCodingDefect"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="scope.row.noneCodingDefect > 0" class="to-child-page" @click="toMRList(scope.row, 6)">{{scope.row.noneCodingDefect}}</span>
                        <span v-else>{{scope.row.noneCodingDefect}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="非编码缺陷率"
                    width="130"
                    align="center"
                    prop="noneCodingDefectRate"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="scope.row.noneCodingDefectRate !== undefined">{{getZeroTwoNum(scope.row.noneCodingDefectRate * 100)}}%</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="国标平均得分"
                    width="110"
                    align="center"
                    prop="nationAvgScore"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    label="院标平均扣分"
                    width="110"
                    align="center"
                    prop="hospitalAvgDeduction"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    label="非编码缺陷提示汇总"
                    align="center"
                    prop="noneCodingTipCount"
                    show-overflow-tooltip
                    min-width="300">
                    <template slot-scope="scope">
                        <span v-if="scope.$index % 2 === 0">{{scope.row.noneCodingTipCount}}类</span>
                        <el-table
                            v-else
                            :data="scope.row.noneCodingTip"
                            :stripe="false"
                            :border="false"
                            style="width: 100%">
                            <el-table-column
                                type="index"
                                label="序号"
                                align="center"
                                width="50">
                            </el-table-column>
                            <el-table-column
                                prop="key"
                                label="提示"
                                header-align="center"
                                min-width="180">
                            </el-table-column>
                            <el-table-column
                                prop="value"
                                label="例数"
                                align="center"
                                sortable
                                width="80">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.value > 0" class="to-child-page" @click="toMRList(scope.row, 6, scope.row.key)">{{scope.row.value}}</span>
                                    <span v-else>{{scope.row.value}}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script>
    import {getSummaryAnalysisList} from '@/api/summary-list/department'
    import {getZeroTwoNum} from '@/utils/filters'
    import BtnGroup from '@/components/BtnGroup'
    import FileSaver from 'file-saver'
    import ExcelJS from 'exceljs'

    export default {
        name: 'index',
        data () {
            return {
                // 按钮显示
                showBtn: ['goBack', 'toExport'],
                // 表格数据
                tableData: [],
                // 排序字段
                sortMap: {},
                // 数据总数
                total: 0,
                // 当前页
                currentPage: 1,
                // 每页数量
                pageSize: 20,
                // 表格高度
                tableHeight: 100,
                // 排序方式
                sortType: '',
                // 全局搜索内容，用于翻页等不传参时使用数据
                globalForm: {},
                // 使用储存的数据，不去请求
                useStore: false,
                // 导出的全部数据
                allexportData: []
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStore = this.$route.query.tags === 'tags'
            let height = document.documentElement.clientHeight - 219 - 10 - 78 - 32 + 78
            this.tableHeight = height > 107 ? height : 107
            this.initPage()
        },
        mounted () {
            window.onresize = () => {
                // 其他元素高度60+50+48 10=距离底部边距 78=分页组件高度 5=适应性调整
                let height = document.documentElement.clientHeight - 219 - 10 - 78 - 32 + 78
                this.tableHeight = height > 107 ? height : 107
            }
        },
        methods: {
            getZeroTwoNum,
            /**
             * 初始化页面参数
             */
            initPage () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (query) {
                    this.currentPage = query.pageIndex || 1
                    this.pageSize = query.pageSize || 20
                    this.sortType = query.orderBy
                }
            },
            /**
             * 单元格class名
             */
            colClass ({rowIndex, columnIndex}) {
                if (rowIndex % 2 === 1 && columnIndex === 6) {
                    return 'inner-table-style'
                }
                return ''
            },
            /**
             * 翻页
             */
            changePage () {
                this.submitSearch()
            },
            /**
             * 获取机构名称
             * @param id 机构id
             */
            getCurrnetOrg (id) {
                let mechanismList = this.getLocalStorage('userInfo', 'mechanism')
                let res = mechanismList.filter(item => item.id === id)
                return res.length ? res[0].name : ''
            },
            /**
             * 提交查询
             * @param form 筛选条件
             */
            submitSearch (form) {
                let data = form || this.globalForm
                this.globalForm = data
                let params = {
                    start: data.start,
                    end: data.end,
                    orgId: data.orgId,
                    department: data.department,
                    departmentName: data.departmentName,
                    coder: data.coder,
                    isLast: data.isLast,
                    resident: data.resident
                }
                if (this.getSession(this.$route.name, 'getSummaryAnalysisList') && this.useStore) {
                    this.useStore = false
                    let res = this.getSession(this.$route.name, 'getSummaryAnalysisList')
                    if (res.code.toString() === '200') {
                        this.tableData = []
                        res.data.forEach(item => {
                            this.tableData.push(item)
                            let arr = item.noneCodingTip.map(it => {
                                return {
                                    ...it, departmentCode: item.departmentCode, departmentName: item.departmentName, resident: item.resident
                                }
                            })
                            this.tableData.push({noneCodingTip: arr})
                        })
                    }
                } else {
                    params.groupType = 1
                    getSummaryAnalysisList(params).then(res => {
                        this.useStore = false
                        this.setSession(this.$route.name, {getSummaryAnalysisList: res})
                        if (res.code.toString() === '200') {
                            this.tableData = []
                            res.data.forEach(item => {
                                this.tableData.push(item)
                                let arr = item.noneCodingTip.map(it => {
                                    return {
                                        ...it, departmentCode: item.departmentCode, departmentName: item.departmentName, resident: item.resident
                                    }
                                })
                                this.tableData.push({noneCodingTip: arr})
                            })
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
                this.setGetStore(this.$route.name, params)
            },
            /**
             * 导出医师缺陷类型列表
             */
            toExport () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (!params.orderBy) params.orderBy = '`deduction` desc'
                params.groupType = 1
                this.$store.dispatch('UpdateLoadingText', '0%')
                this.$store.dispatch('UpdateIsExport', true)
                this.$store.dispatch('UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequest(params)
            },
            /**
             * 发送请求
             * @param params 请求参数
             */
            sendRequest (params) {
                let allIndex = Math.ceil(this.total / 1000)
                getSummaryAnalysisList(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data)
                        if (params.pageIndex < allIndex) {
                            this.sendRequest({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataList('医师缺陷类型分析', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('UpdateIsExport', false)
                        this.$store.dispatch('UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 导出excel表头
             */
            getHeader () {
                return [{
                    header: '住院医师', key: 'resident', width: 24
                }, {
                    header: '总病案例数', key: 'total', width: 16
                }, {
                    header: '非编码缺陷病案例数', key: 'noneCodingDefect', width: 16
                }, {
                    header: '非编码缺陷率', key: 'noneCodingDefectRate', width: 16
                }, {
                    header: '国标平均得分', key: 'nationAvgScore', width: 16
                }, {
                    header: '院标平均扣分', key: 'hospitalAvgDeduction', width: 16
                }, {
                    header: '非编码缺陷提示汇总', key: 'noneCodingTipCount', width: 10
                }, {
                    header: '非编码缺陷提示汇总', key: 'noneCodingTipCount', width: 48
                }, {
                    header: '非编码缺陷提示汇总', key: 'noneCodingTipCount', width: 10
                }]
            },
            /**
             * 导出列表excel
             */
            exportDataList (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                worksheet.columns = this.getHeader()
                for (let i = 0; i < data.length; i++) {
                    data[i].noneCodingDefectRate = Math.abs(getZeroTwoNum(data[i].noneCodingDefectRate * 100)) + '%'
                    worksheet.addRow(data[i])
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('UpdateLoadingText', rate)
                }
                worksheet.mergeCells('G1:I1')
                worksheet.mergeCells('G2:I2')
                worksheet.getCell('G2').value = data[0].noneCodingTipCount + '类'
                worksheet.getRow(1).alignment = {vertical: 'middle', horizontal: 'center'}
                worksheet.getRow(2).alignment = {vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('G').alignment = {vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('I').alignment = {vertical: 'middle', horizontal: 'center'}
                worksheet.getCell('G3').value = '序号'
                worksheet.getCell('H3').value = '提示'
                worksheet.getCell('I3').value = '例数'
                let noneCodingTip = data[0].noneCodingTip
                for (let i = 0; i < noneCodingTip.length; i++) {
                    worksheet.getCell(`G${i + 4}`).value = i + 1
                    worksheet.getCell(`H${i + 4}`).value = noneCodingTip[i].key
                    worksheet.getCell(`I${i + 4}`).value = noneCodingTip[i].value
                }
                // 取提示汇总最大数量
                let maxLine = noneCodingTip.length
                worksheet.mergeCells(`A3:A${maxLine + 3}`)
                worksheet.mergeCells(`B3:B${maxLine + 3}`)
                worksheet.mergeCells(`C3:C${maxLine + 3}`)
                worksheet.mergeCells(`D3:D${maxLine + 3}`)
                worksheet.mergeCells(`E3:E${maxLine + 3}`)
                worksheet.mergeCells(`F3:F${maxLine + 3}`)
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('UpdateLoadingText', '100%')
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                })
            },
            /**
             * 前往病案列表
             * @param row 行数据
             * @param val 参数值
             * @param errReason 提示项
             */
            toMRList (row, val, errReason) {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                let params = {
                    ...query,
                    department: row.departmentCode,
                    departmentName: '',
                    // departmentName: row.departmentName,
                    defectSate: val,
                    resident: row.resident,
                    pageIndex: 1,
                    orderBy: ''
                }
                if (errReason) params.errReason = errReason
                this.$store.dispatch('search/coverSearchFormItem', {
                    pageName: 'DoctorSummaryAnalysisMRList',
                    query: params
                })
                this.$router.push({name: 'DoctorSummaryAnalysisMRList'})
            }
        },
        components: {
            BtnGroup
        },
        beforeDestroy () {
            window.onresize = null
        }
    }
</script>

<style lang="scss" scoped>
    .score-summary-container {
        height: calc(100% - 10px);
        .page-content {
            height: calc(100% - 54px);
            background: #fff;
            padding: 0 10px;
        }
        .head {
            display: flex;
            justify-content: space-between;
            align-items: center;
            h3 {
                font-size: 16px;
                color: #000;
                font-weight: 600;
                line-height: 48px;
            }
        }
    }
    /deep/.el-table tbody tr:hover>td {
        background-color:#ffffff!important
    }
</style>
